package org.lex.ftp.queue;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

import org.lex.ftp.ui.StatusBar;
import org.lex.ftp.ui.explorer.FTPExplorer;
import org.lex.ftp.util.Utilities;
import org.lex.progress.Progress;
import org.lex.utils.text.SizeFormat;


public class StatusMonitorTimer extends Timer implements ActionListener {
	private static final int delay = 1000;
	private FTPExplorer explorer = null;
	private Progress progress = null;

	public StatusMonitorTimer(FTPExplorer explorer) {
		super(delay, null);
		this.addActionListener(this);
		this.explorer = explorer;
	}

	public void monitor(Progress progress) {
		this.progress = progress;
		this.start();
	}

	public void actionPerformed(ActionEvent e) {
		if (progress.getProgress() >= progress.getMaximum()) {
			explorer.app.getStatusPane().clear();
			this.stop();
			return;
		} else
			this.refreshStatusPane();
	}

	public void refreshStatusPane() {
		if (null != this.progress && true == explorer.isConnected())
		// && true == explorer.getQueueHandler().isTransferring() )
		{
			long max = progress.getMaximum();
			long completed = progress.getProgress();
			int percent = (int) (completed * 100 / max);
			long elapsed = progress.elapsedTime();
			long speed = completed * 1000L / elapsed;
			speed = (speed == 0L ? 1L : speed);
			long remained = (max - completed) * 1000 / speed;
			String progressString = SizeFormat.autoFormat(completed) + "B ( " + SizeFormat.autoFormat(speed) + "B/s )";
			String elapsedTime = Utilities.formatTime(elapsed);
			String remainedTime = Utilities.formatTime(remained);
			StatusBar statusPane = explorer.app.getStatusPane();
			statusPane.setProgressString(progressString);
			statusPane.setPercent(percent);
			statusPane.setElapsedTime(elapsedTime);
			statusPane.setRemainedTime(remainedTime);
		}
	}
}
